package com.data.interceptor;

import com.data.util.HtmlGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Enumeration;

public class HtmlGeneratorInterceptor implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.debug("执行到这儿了。。。。。。。。。。。。。。。。。");
        HttpServletRequest request1 = (HttpServletRequest) request;
        Enumeration enu = request.getParameterNames();
        StringBuilder stringBuilder = new StringBuilder("");
        while (enu.hasMoreElements()) {
            String paraName = (String) enu.nextElement();
            stringBuilder.append(paraName).append(request.getParameter(paraName));
        }
        //生成HTML文件名称
        String pageName = String.valueOf(stringBuilder.append(request.getRequestURI()).toString().hashCode()) + ".html";


//        String page = String.valueOf(stringBuilder.toString().hashCode());
//        String path = "/root/html/" + page + ".html";
//        logger.debug(path);
//        File file = new File(path);
//        if (file.isFile() && file.length() > 0) {
//            logger.debug("这是一个文件.......................");
//            String data = readFile(file);
//            response.getWriter().write(data);
//            response.getWriter().flush();
//            return false;
//        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    public static String readFile(File file) {
        StringBuilder result = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行
                result.append(System.lineSeparator() + s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }
}
